// Loesung_von_Aufgabe_3.7_9_Ladung_im_Vektorfeld

PVector[][] E = new PVector[20][20]; // zweidimesionales Array
PVector ladungPosition = new PVector(260, 260); // Startwert der Ladung

float skalierung = 800 / 20; // Größe einer Zelle

void setup()
{
  size(800, 800);

  // Array wird mit Werten gefüllt und die Werte werden mit normalize() auf 1 normiert
  for (int y = 0; y < 20; y++)
  {
    for (int x = 0; x < 20; x++)
    {
      E[y][x] = new PVector(1 + random(-0.75, 0.75), sin(x * 0.3) + random(-0.75, 0.75)).normalize();
    }
  }
}

void draw()
{
  background(255, 255, 255);

  // Das Vektorfeld wird gezeichnet
  for (int y = 0; y < 20; y++)
  {
    for (int x = 0; x < 20; x++)
    {
      noFill();
      stroke(0, 0, 0);
      strokeWeight(1);

      line(x * skalierung + 10, y * skalierung+ 10, x * skalierung + E[y][x].x*20+ 10, y * skalierung + E[y][x].y*20 + 10);

      noStroke();
      fill(0, 0, 0);
      ellipse(x * skalierung + E[y][x].x*20 + 10, y * skalierung + E[y][x].y*20 + 10, 7, 7);
    }
  }

  // Die Ladung bewegt sich in Richtung des Pfeils, der sich zusammen mit der Ladung in einer Zelle befindet 
  ladungPosition.add(E[(int)ladungPosition.y / 40][(int)ladungPosition.x / 40]);

  // Ladung wird gezeichnet
  noStroke();
  fill(255, 0, 0);
  ellipse(ladungPosition.x, ladungPosition.y, 15, 15);

  // Erreicht die Ladung den Rand, stoppt die Simulation
  if (ladungPosition.x >= 790 || ladungPosition.y <= 10)
    noLoop();
}